package com.wenjie.common.reRequest;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 将 默认的请求对象 替换为 缓存body的请求对象，即 HttpServletRequest -> CacheBodyRequest
 *
 * @author PanXun
 */
@Component
public class ReplaceHttpRequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        CacheBodyRequest cacheBodyRequest = new CacheBodyRequest(httpServletRequest);

        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        CaptureResponseWrapper responseWrapper = new CaptureResponseWrapper(httpServletResponse);

        chain.doFilter(cacheBodyRequest, responseWrapper);

        String capturedResponse = responseWrapper.getCapturedResponse();
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(capturedResponse);

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
